# -*- coding: utf-8 -*-
import json

from django.core.paginator import Paginator
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from home.model import Article_Info, Article_Detail
from home.model.article_info import Article_Info_Serializer
from home.services.article_info_service import Article_Info_Service
from home.utils.post_parameter_getter import ParamGetter


@csrf_exempt
def save_article(request):
	"""
		文章信息保存服务
		:param request:
		:return:
		"""
	if request.method == "POST":
		article_Info_Service = Article_Info_Service()
		article_Info = Article_Info()
		article_Detail = Article_Detail()
		
		article_Info.id = ParamGetter.getParam(request, "id")
		article_Info.category_id = ParamGetter.getParam(request, "article_category")
		article_Info.title = ParamGetter.getParam(request, "article_title")
		article_Info.author = ParamGetter.getParam(request, "author", request.session["login_user_name"])
		article_Info.summary = ParamGetter.getParam(request, "article_summary", "暂无摘要")
		article_Info.comment_count = ParamGetter.getParam(request, "comment_count", 0)
		article_Info.view_count = ParamGetter.getParam(request, "view_count", 0)
		article_Info.original = ParamGetter.getParam(request, "original", False)
		article_Info.pic_id = ParamGetter.getParam(request, "pic_id")
		article_Info.create_time = ParamGetter.getParam(request, "create_time")
		article_Detail.content = ParamGetter.getParam(request, "article_content")
		article_Detail.create_time = ParamGetter.getParam(request, "create_time")
		
		try:
			# 持久化到数据库中
			article_Info_Service.save_article(article_Info, article_Detail)
			result = {"status": "success", "message": "新闻保存成功！"}
		except Exception as err:
			result = {"status": "error", "message": "新闻信息保存时发生异常！"}
			import traceback
			print(traceback.format_exc())
	return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def article_operator(request, article_id):
	"""
	新闻信息查询服务：根据新闻D查询或者删除指定的新闻信息
	:param request:
	:return:
	"""
	if request.method == "GET":
		article_info_service = Article_Info_Service()
		article_info = article_info_service.get_with_id(article_id)
		if article_info is not None:
			result = {"status": "success", "message": "新闻信息查询成功！",
			          "user": json.dumps(Article_Info_Serializer.to_json_object(article_info), ensure_ascii=False)}
		else:
			result = {"status": "error", "message": "新闻信息不存在！ID=" + article_id}
	if request.method == "DELETE":
		article_Info_Service = Article_Info_Service()
		if article_Info_Service.delete_article(article_id):
			result = {"status": "success", "message": "新闻信息删除成功！ID=" + article_id}
		else:
			result = {"status": "error", "message": "新闻信息删除失败！ID=" + article_id}
	return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def filter_articles(request):
	"""
		文章信息搜索查询服务：根据过滤条件搜索文章信息列表，分页
		:param request:
		:return:
		"""
	if request.method == "PUT":
		article_Info_Service = Article_Info_Service()
		category_id = ParamGetter.getParam(request, "category_id")
		title = ParamGetter.getParam(request, "title")
		author = ParamGetter.getParam(request, "author")
		original = ParamGetter.getParam(request, "original")
		label = ParamGetter.getParam(request, "label")
		max_count = ParamGetter.getParam(request, "max_count", 20)
		current_page = ParamGetter.getParam(request, "current_page", 1)
		try:
			articles = article_Info_Service.filter_article_info(category_id, title, author, original, label)
			'''分页功能：其实是查询全部在内存里分页'''
			paginator = Paginator(articles, max_count)
			paged_articles = paginator.page(current_page)
			result = {"status": "success", "message": "新闻信息查询成功！",
			          "articles": json.dumps(Article_Info_Serializer.to_json_objects(paged_articles.object_list),
			                                 ensure_ascii=False)}
		except Exception as err:
			result = {"status": "error", "message": "新闻信息查询时发生异常！", "articles": []}
			import traceback
			print(traceback.format_exc())
		return HttpResponse(json.dumps(result), content_type="application/json")


def view_article(request, article_id):
	"""
		文章信息阅读服务：根据文章ID查询文章信息，并且记录阅读相关数据信息
		:param request:
		:return:
		"""
	if request.method == "GET":
		article_info_service = Article_Info_Service()
		article_info = article_info_service.get_with_id(article_id)
		if article_info is not None:
			article_info.increase_view_count()
			article_info.save()
			# 获取详细内容
			article_content = article_info_service.get_content_with_id(article_id)
			result = {"status": "success", "message": "新闻信息查询成功！",
			          "article": json.dumps(Article_Info_Serializer.to_json_object(article_info), ensure_ascii=False),
			          "content": article_content
			          }
		else:
			result = {"status": "error", "message": "新闻信息不存在！ID=" + article_id}
		return HttpResponse(json.dumps(result), content_type="application/json")
